<template>
    <div class="haloTreeCon me">
        <!--<h3 style="font-size:16px;margin:14px auto">招商局集团</h3>-->
        <NTree
            ref='tree'
            :treeData="treeDataNew"
            :options.sync="options1"
            @node-click="itemClick1"
            @add-node="addNode"
            :key="3"
        >
        </NTree>
    </div>

</template>

<script>
    import Vue from 'vue';
    // import axios from 'axios';
    import NTree from '@/components/userManager/dialog/tree/tree.vue';

    NTree.install = function(Vue) {
        Vue.component('NTree', NTree);
    };
    //  import {ZTree} from './../dist/vue2-tree.min'
    //  import './../dist/vue2-tree.min.css'
    Vue.use(NTree)

    const Tree3 = {
        name: 'Tree3Me',
        data: function () {
            return {
                options1: {
                    showCheckbox: true,
                    halfCheck: false, //控制父框是否需要半钩状态

                    lazy: true,
                    load: this.loadNodeNew,

                    showSearch: false,

                    rootName: '我的组织',

                    iconClass: {
                        close: 'icon-expand',
                        open: 'icon-collapse',
                        add: 'icon-add'
                    },
                    iconStyle: {
                        color: '#108ee9'
                    },

                    dynamicAdd: false,
                    // function  handle display add button
                    // return true or false
                    dynamicAddFilter: (node) => {
                        if (node.type === 1 || node.type === 2) {
                            return true
                        }
                        return false
                    },
                    // function handle add node; the new node must have `dynamicAdd` property
                    // the tree component rely on this show editor
                    // return Promise
                    dynamicAddNode: this.addNode,
                    // function handle save node; the new node must have `dynamicSaveNode` property
                    // the tree component rely on this save node
                    // return Promise
                    dynamicSaveNode: this.saveNode,
                    // function handle
                    // return String
                    leafIcon: this.leafIcon,

                    search: {
                        useInitial: true,
                        useEnglish: false,
                        customFilter: null
                    }
                },
                treeDataNew: []
            }
        },
        created(){
            // this.getDept();

            this.treeData.length && (this.treeDataNew = JSON.parse(JSON.stringify(this.treeData[0])))
        },
        props:["url","type",'treeData','isLazy','treeDataSave','levelNum','treeDataLevelSave'],
        mounted () {
            // this.loadTreeData();
        },
        watch:{
            treeData(newVal,oldVal){
                if (newVal && newVal.length) {
                    console.log(this.isLazy,'this.isLazy');

                    // if (!this.isLazy) {
                    //     this.handleTreeData(newVal);
                    //     return;
                    // } 

                    this.$emit('update:levelNum',1);
                    
                    var dataTree = JSON.parse(JSON.stringify(this.treeData[0]))


                    dataTree.forEach((k,index)=>{
                            var personCheck = false,payCheck = false;
                            if (this.treeDataLevelSave.length) {
                                for (let r = 0; r < this.treeDataLevelSave[0].length;r++) {
                    
                                    if (k.level_num ===  this.treeDataLevelSave[0][r].level_num) {
                                        k.checked = true;
                                        if (this.treeDataLevelSave[0][r].pay) {
                                            payCheck = true
                                        }
                                        if (this.treeDataLevelSave[0][r].personnel) {
                                            personCheck = true;
                                        }
                                        break;
                                    }
                                }
                            }
                            k.open = true;

                            Vue.set(k,'treeList',[{
                                "type":'personal',
                                "descr": "人事",
                                "descrshort": "招商工业",
                                "deptid":dataTree[0].deptid,
                                "personnel": 0,
                                "pay": 0,
                                "treeList": null,
                                'checked':personCheck
                            },{
                                "type":'money',
                                "descr": "薪酬",
                                "descrshort": "招商工业",
                                "deptid":dataTree[0].deptid,
                                "personnel": 0,
                                "pay": 0,
                                "treeList": null,
                                'checked':payCheck
                            }])
 
                    })
                    
                    this.loadNodeNew(dataTree[0]);
                    // debugger;
                    console.log(dataTree,'dataTreeTest');
                    this.treeDataNew = dataTree;


                }

            }
        },
        methods: {

            postAjax:function(setid,deptid){
                var type = this.type ==="employee"?1:2;
                if (this.type !== 'employee') {
                    
                    this.Axios.StringPost(this.url ,{setid:setid || '',parent_deptid:deptid || '',type:type},true).then(res => {
                        var result = res.data.datas.deptmune;
                        // result[0].checked = true;
                        this.treeData1 = result;
                        
                    })
                } else {
                    this.Axios.StringPost(this.url ,{setid:setid || '',parent_deptid:deptid || '',type:type},true).then(res => {
                        var result = res.data.datas.deptmune;
                        // result[0].checked = true;
                        this.treeData1 = result;
                        
                    })
                                
                }
                
            },
        	getDept:function(depid){
	    		var params={
	    			depid:depid || '',
	    		}
	    		this.Axios.Post(this.URL.leaveBydeptAuth.url,params).then(res =>{
	    			this.treeData1 = res.data.datas.showDept;

	    		})
	    	},
            getId:function(node){
                let keys = node.key.split("-");
                let ids = keys[keys.length-1].split(",");
                var setid = ids[1];
                var deptid = ids[2];
                return {
                    setid:setid,
                    deptid:deptid,
                    shortName:node.descr
                };
            },
            /**
             * generate key 0-1-2-3
             * this is very important function for now module
             * @param treeData
             * @param parentKey
             * @returns {Array}
             */
            generateKey (treeData = [], parentKey) {
                treeData = treeData.map((item, i) => {
                    parentKey ? item.key = parentKey + '-' + i+","+item.id + ","+item.parentId : item.key = i+","+item.id + ","+item.parentId;
                    // item.key = parentKey + '-' + i.toString();

                    if (item.hasOwnProperty('children') && item.children.length > 0) {
                        this.generateKey(item.children, item.key)
                    }

                    return item;
                })
                return treeData;
            },
            /**
             * get parent node
             * @param node { Object }
             * @param treeData { Array }
             * @returns { Object }
             */
            getParentNode (node, treeData) {
                let tem,arr = [];
                let postions = node.key.split('-');
                for (var i = 0,len=postions.length;i<len;i++) {
                    arr.push(postions[i].split(',')[0]);
                }
                for (let [index, item] of arr.entries()) {
                    switch (index) {
                        case 0:
                            tem = treeData[item];
                            break;
                        default:
                            tem = tem.children[item];
                    }
                }

                return tem
            },
            loadTreeData: function () {
                let treeData = [
                    {
                        id: 1,
                        label: '二层集团总部',
                        type: 1,
                        open: true,
                        checked: false,
                        nodeSelectNotAll: false,//新增参数，表示父框可以半钩状态
                        parentId: null,
                        visible: true,
                        searched: false,
                        children: [
                            {
                                id: 1001,
                                label: '招商国际',
                                open: false,
                                checked: false,
                                nodeSelectNotAll: false,//新增参数，表示父框可以半钩状态
                                parentId: 1,
                                visible: true,
                                searched: false
                            },{
                                id: 1001,
                                label: '招商金融',
                                open: false,
                                checked: false,
                                nodeSelectNotAll: false,//新增参数，表示父框可以半钩状态
                                parentId: 1,
                                visible: true,
                                searched: false
                            },{
                                id: 1001,
                                label: '招商证券',
                                open: false,
                                checked: false,
                                nodeSelectNotAll: false,//新增参数，表示父框可以半钩状态
                                parentId: 1,
                                visible: true,
                                searched: false
                            }

                        ]
                    },
                    {
                        id: 2,
                        label: '二层集团总部',
                        open: false,
                        type: 2,
                        checked: false,
                        nodeSelectNotAll: false,
                        parentId: null,
                        visible: true,
                        searched: false
                    },
                    {
                        id: 3,
                        label: '二层集团总部',
                        open: false,
                        type: 3,
                        checked: false,
                        nodeSelectNotAll: false,
                        parentId: null,
                        visible: true,
                        searched: false,
                        leaf: true
                    },
                    {
                        id: 4,
                        label: '二层集团总部',
                        open: false,
                        type: 4,
                        checked: false,
                        nodeSelectNotAll: false,
                        parentId: null,
                        visible: true,
                        searched: false
                    }
                ]

//                this.treeData1 = this.generateKey(treeData, 0);
                this.treeData1 = treeData
            },
            async loadingChild (node, index) {
                try {

					
                    let idsGroup = this.getId(node);

                    let data = await this.Axios.Post(this.URL.leaveBydeptAuth.url,{depid:node.deptid});
  
                    let tem = this.getParentNode(node, this.treeData1)
                    Vue.set(tem, 'children', data.data.datas.showDept);                      
                    
                   


                    // Promise.resolve(data);
                } catch (e) {
                    // Promise.reject(e);
                }
            },

            handleTreeData(data, start, end = 0) {
                //先找到列表运算末级与末级的上一级
                //将末级push到上一级
                //依次运算整合到第一级数据  从而完成树状结构
                const len = data.length;

                if (!start) {
                    start = len - 1;
                }

                // data[0].splice(0,0,hrObj,payObj);
                for (let index = start; index > end; index--) {
                    data[index - 1].forEach(x => {
                    data[index].forEach(k => {
     
                        if (k.level_num.indexOf(x.level_num) >= 0) {
                            if (!x.treeList) {
                                x.treeList = [];
                            }

                        if (!k.treeList) {
                           k.treeList=[];
                        }   


                        var hrObj= {
                            "type":'personal',
                            "descr": "人事",
                            "descrshort": "招商工业",
                            "deptid":x.deptid,
                            "personnel": 0,
                            "pay": 0,
                            "treeList": null
                        }

                        var payObj={
                            "type":'money',
                            "descr": "薪酬",
                            "descrshort": "招商工业",
                            "deptid":x.deptid,
                            "personnel": 0,
                            "pay": 0,
                            "treeList": null
                        }

                        k.treeList.splice(0,0,hrObj,payObj);


                            // data.CheckDept.forEach(ele => {
                            //   if (k.deptid == ele.department_id) {
                            //     k.personnel = ele.personnel;
                            //     k.pay = ele.pay;
                            //   }
                            // });

                            x.treeList.push(k);



                        }

                    });
                    });
                }

            },


           loadNode(node, index) {
                const level = node.level;

                if (!this.treeData[level].length) {
                    Vue.set(node, 'children', []); 
                }
                Vue.set(node, 'treeList', this.treeData[level]); 



            },


            async loadNodeNew(node, resolve) {
                console.log(node.level,'node.level');
                const level = node.level;

                if (level === this.treeDataSave.length) {
                    return ;
                }

                if (node.level + 1> this.levelNum) {
                    this.$emit('update:levelNum',node.level + 1);
                }

                let dataArr = [];
                
                this.treeDataSave[level].forEach((ele, i, arr) => {
                    if (ele.level_num.indexOf(node.level_num) >= 0) {

                        var personCheck = false,payCheck = false;

                        if (this.treeDataLevelSave[level] && this.treeDataLevelSave[level].length) {
                           
                            for (let r = 0; r < this.treeDataLevelSave[level].length;r++) {
                                if (ele.level_num ===  this.treeDataLevelSave[level][r].level_num) {
                                    Vue.set(ele,'checked',true);
                                   
                                    // ele['checked'] = true;
                                    if (this.treeDataLevelSave[level][r].pay || node.pay) {
                                        ele.pay = 1;
                                        payCheck = true
                                    }
                                    if (this.treeDataLevelSave[level][r].personnel || node.personnel) {
                                        ele.personnel = 1;
                                        personCheck = true;
                                    }
                                    break;
                                }
                            }                            
                        }

                        var hrObj= {
                            "type":'personal',
                            "descr": "人事",
                            "descrshort": "招商工业",
                            "deptid":ele.deptid,
                            "personnel": 0,
                            "pay": 0,
                            checked:personCheck,
                            "treeList": null
                        }

                        var payObj = {
                            "type":'money',
                            "descr": "薪酬",
                            "descrshort": "招商工业",
                            "deptid":ele.deptid,
                            "personnel": 0,
                            "pay": 0,
                            checked:payCheck,
                            "treeList": null
                        }
                        // ele.treeList = [];
    
                        Vue.set(ele,'treeList',[hrObj,payObj])
                        // ele.treeList.splice(0,0,hrObj,payObj);
                        dataArr.push(ele);
                    }
                });
  
                Vue.set(node, 'treeList', node.treeList.concat(dataArr));
           
            },


            itemClick1 (node) {

                let idsGroup = this.getId(node);
                this.$emit('update:returnValue',idsGroup);

            },
            async addNode (item) {
                let parent = this.getParentNode(item, this.treeData1)
                let node = {
                    id: 2,
                    label: '一级节点',
                    open: false,
                    checked: false,
                    nodeSelectNotAll: false,
                    parentId: null,
                    visible: true,
                    searched: false
                }
                if (!item.hasOwnProperty('children') || item.children.length === 0) {
                    await this.loadingChild(parent)
                }
                parent.open = true

                parent.children.splice(0, 0, Object.assign({}, { dynamicAdd: true, loaded: true }, node))

//                this.generateKey(parent.children, parent.key) // regenerate key
                return Promise.resolve(parent.children)

            },
            async saveNode (item, e) {
                if (!e.target.value) {
                    return
                }
                try {
                    // todo sent data to sever
                    delete item.dynamicAdd // 删除属性

                    Vue.set(item, 'label', e.target.value)

                    e.target.value = ''

                    return Promise.resolve(item) // server return data with id
                } catch (e) {
                    return Promise.reject(e)
                }



            },
            /**
             * 叶子结点 的 icon class
             * @param node
             * @returns {*}
             */
            leafIcon (node) {
                // filter type and return icon class

                if (node.type === 1 || node.type === 2) {
                    return ''
                }
                return 'icon-square'
            }

        }
    }

    export default Tree3
</script>

<style  scoped>
.haloTreeCon{
    padding-top:20px;
}
</style>
